package org.sauceggplant.item.man.data.h2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class H2ConnectionUtil {

    private static final Logger logger = LoggerFactory.getLogger(H2ConnectionUtil.class);

    private static Properties PROPERTIES = new Properties();

    private static final String DRIVER_KEY = "jdbc.driver";

    private static final String URL_KEY = "jdbc.url";

    static {
        InputStream inputStream = H2ConnectionUtil.class.getResourceAsStream("/db.properties");
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(H2ConnectionUtil.class.getName(), e);
        }
        try {
            PROPERTIES.load(inputStreamReader);
        } catch (IOException e) {
            logger.error(H2ConnectionUtil.class.getName(), e);
        }
    }

    public Connection getConnection() {
        try {
            Class.forName(PROPERTIES.getProperty(DRIVER_KEY));
        } catch (ClassNotFoundException e) {
            logger.error(H2ConnectionUtil.class.getName(), e);
        }
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(PROPERTIES.getProperty(URL_KEY));
        } catch (SQLException e) {
            logger.error(H2ConnectionUtil.class.getName(), e);
        }
        return connection;
    }
}
